package javacommon.web.tag;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import static javacommon.util.ReflectionUtils.*;

public class Select extends SimpleTagSupport {
	private String name;
	private Object list;
	private String label;
	private Object value;
	private String listKey;
	private String listValue;
	@Override
	public void doTag() throws JspException, IOException {
		PageContext context = (PageContext) getJspContext();
		JspWriter out = context.getOut();
		if (label != null) {
			out.println(label + ":");
		}
		out.println("<select name='" + name + "'>");
		if (list instanceof Map) {
			Map<Object, Object> m = (Map<Object, Object>) list;
			Set<Object> names = m.keySet();
			for (Object key : names) {
				if (value != null && (value == key || value.equals(key)))
					out.println("<option value='" + key
							+ "' selected='selected'>" + m.get(key)
							+ "</option>");
				else
					out.println("<option value='" + key + "'>" + m.get(key)
							+ "</option>");
			}
		} else if (list.getClass().isArray()) {
			int leng = Array.getLength(list);
			for (int i = 0; i < leng; i++) {
				Object kv = Array.get(list, i);
				if(value!=null&&(value==kv||value.equals(kv)))
					out.println("<option value='" + kv + "' selected='selected'>" + kv + "</option>");
				else
				out.println("<option value='" + kv + "'>" + kv + "</option>");
			}
		}else if(list instanceof Collection){
			Collection collection = (Collection) list;
			Iterator iter = collection.iterator();
			while(iter.hasNext()){
				Object obj = iter.next();//当前对象
				Class claz = obj.getClass();
				Object _key =invokeMethod(getter(claz, listKey), obj);
				Object _value =invokeMethod(getter(claz, listValue), obj);
				if(value!=null&&(value==_key||value.equals(_key))){
					out.println("<option value='" + _key + "' selected='selected'>" + _value + "</option>");
				}else{
					out.println("<option value='" + _key + "'>" + _value + "</option>");
				}
			}
		}
		out.println("</select>");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public Object getList() {
		return list;
	}

	public void setList(Object list) {
		this.list = list;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public String getListKey() {
		return listKey;
	}

	public void setListKey(String listKey) {
		this.listKey = listKey;
	}

	public String getListValue() {
		return listValue;
	}

	public void setListValue(String listValue) {
		this.listValue = listValue;
	}
}
